package org.enhance.common.util;

import org.enhance.common.exception.EnhanceRuntimeException;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpDownloadUtil {
	private HttpDownloadUtil() {
		throw new IllegalStateException("Constant class");
	}

	public static void download(String url, String outPutFile) {
		try (InputStream inputStream = getInputStream(url)) {
			Assertion.notNull(inputStream, "获取:" + url + ";下载流失败");
			try (FileOutputStream fileOutputStream = new FileOutputStream(outPutFile)) {
				int len;
				byte[] data = new byte[1024];
				while ((len = inputStream.read(data)) != -1) {
					fileOutputStream.write(data, 0, len);
				}
			}
		} catch (Exception e) {
			throw new EnhanceRuntimeException(e);
		}
	}

	public static InputStream getInputStream(String httpUrl) throws IOException {
		URL url = new URL(httpUrl);
		HttpURLConnection httpURLConnection = null;
		try {
			httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setConnectTimeout(3000);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setRequestMethod("GET");
			int responseCode = httpURLConnection.getResponseCode();
			if (responseCode == 200) {
				return httpURLConnection.getInputStream();
			}
			return null;
		} finally {
			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}
		}
	}
}